package com.eugenes.design;

import com.eugenes.collections.MyArrayList;
import com.eugenes.collections.MyList;
import com.eugenes.util.Observable;
import com.eugenes.util.Observer;
import org.joda.time.DateTime;

public class SkiPassCheckpoint implements Checkpoint,
        Observable<SkiPassEvent> {

    MyList<Observer<? super SkiPassEvent>> observers;

    public SkiPassCheckpoint() {
        observers = new MyArrayList<>();
    }

    public SkiPassCheckpoint(Observer<? super SkiPassEvent> observer) {
        this();
        observers.add(observer);
    }

    @Override
    public boolean pass(Card card) {
        boolean verdict = card.use();
        SkiPassEvent.PassVerdict result = verdict ? SkiPassEvent.PassVerdict.GRANTED :
                SkiPassEvent.PassVerdict.DENIED;
        SkiPassEvent event =
                new SkiPassEvent(new DateTime(), result, this);
        notifyOfEvent(event);
        return verdict;
    }

    @Override
    public boolean registerObserver(Observer<? super SkiPassEvent> observer) {
        observers.add(observer);
        return true;
    }

    @Override
    public boolean unregisterObserver(Observer<? super SkiPassEvent> observer) {
        int indexOfObserver = observers.indexOf(observer);

        if (indexOfObserver == -1) {
            return false;
        } else {
            observers.remove(indexOfObserver);
            return true;
        }
    }

    private void notifyOfEvent(SkiPassEvent event) {
        for (Observer<? super SkiPassEvent> observer : observers) {
            observer.handleEvent(event);
        }
    }
}
